import * as Router from 'koa-router'
import * as Joi from 'joi'
import * as RemarkService from '../services/remark.service'
import * as userService from '../services/user.service'
import { badParams, stats } from '../stats'

const router = new Router({
  prefix: '/api/remark'
})

// 添加评论 只有确认收货的才能评论
router.post('/add', async ctx => {
  const user = await ctx.state.userInfo
  if (!user) throw stats.ERR_NOT_LOGIN
  const schema = Joi.object({
    bookId: Joi.string().required(),
    content: Joi.string().required().min(5).max(50),
    rate: Joi.number().required(),
    dingdanId: Joi.string()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const data = await RemarkService.addRemark(value, user._id)
  ctx.body = {
    stat: 'OK',
    data
  }
})

// 点赞/ 取消点赞
router.post('/deal/thumb', async ctx => {
  const user = await ctx.state.userInfo
  if (!user) throw stats.ERR_NOT_LOGIN
  const schema = Joi.object({
    remarkId: Joi.string().required(),
    flag: Joi.boolean().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const msg = await RemarkService.dealthumb(value, user._id)
  ctx.body = {
    stat: 'OK',
    msg
  }
})

// 详情页的评论列表
router.post('/list', async ctx => {
  const token = ctx.cookies.get('token')
  const schema = Joi.object({
    bookId: Joi.string().required(),
    skip: Joi.number().required(),
    limit: Joi.number().required(),
    flag: Joi.boolean().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  if (token) {
    const user = await userService.userInfo(token)
    const data = await RemarkService.list(value, user._id)
    ctx.body = {
      stat: 'OK',
      data
    }
  } else {
    const data = await RemarkService.list(value)
    ctx.body = {
      stat: 'OK',
      data
    }
  }
})

// 确认/取消订单
router.post('/confirm', async ctx => {
  const user = await ctx.state.userInfo
  const schema = Joi.object({
    dingdanId: Joi.string().required(),
    flag: Joi.boolean().required()
  })
  const { value, error } = schema.validate(ctx.request.body)
  if (error) throw badParams(error.message)
  const res = await RemarkService.confirm(value, user._id)
  if (res) {
    ctx.body = {
      stat: 'OK',
      msg: '成功失败'
    }
  }
})

export default router
